<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success" process-status="finish">
      <el-step title="上传数据"></el-step>
      <el-step title="生成匹配结果"></el-step>
      <el-step title="确认通知方式"></el-step>
      <el-step title="导出匹配结果"></el-step>
    </el-steps>
    <div v-if="active == 0" class="mt30 absolute">
      <el-upload
        drag
        ref="upload"
        class="upload-demo"
        :limit="1"
        accept=".xlsx, .xls, .csv"
        :headers="upload.headers"
        :action="upload.url + '?type=' + upload.type"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-change="handleFileChange"
        :on-success="handleFileSuccess"
        :show-file-list="false"
        :auto-upload="false"
        :on-error="handleFileError"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          点击或将表格拖拽到此处上传
          <div class="upload-tip">支持格式：xls, xlsx, csv</div>
        </div>
      </el-upload>
      <el-link type="primary" class="block mt30" @click="downloadExcel"
        >点此下载导入模板</el-link
      >
      <el-button type="primary" @click="handleConfirm" class="mt60 botlef"
        >下一步</el-button
      >
    </div>

    <div v-else>
      <el-table v-loading="loading" :data="matchingList">
        <el-table-column label="EORI" align="center" prop="eori" />
        <el-table-column
          label="CLIENTS DESCRIPTION"
          align="center"
          prop="clientsDescription"
        />
        <el-table-column
          label="CLIENTS DESCRIPTION IN CHINESE"
          align="center"
          prop="clientsDescriptionInChinese"
        />
        <el-table-column label="MATERIAL" align="center" prop="material" />
        <el-table-column
          label="CLIENTS HS CODE"
          align="center"
          prop="clientsHsCode"
        />
        <el-table-column label="ASIN" align="center" prop="asin" />
        <el-table-column label="COMMODITY" align="center" prop="commodity" />
        <el-table-column label="HS CODE" align="center" prop="hsCode" />
        <el-table-column
          label="Third country duty"
          align="center"
          prop="thirdCountryDuty"
        />
        <el-table-column label="匹配度" align="center" prop="matchingDegree" />
        <el-table-column label="匹配模式" align="center" prop="matchPattern" />
        <el-table-column
          v-if="active === 2"
          label="原海关编码是否有效"
          align="center"
          prop="customsCode"
        />
        <el-table-column
          v-if="active === 2"
          label="备注"
          align="center"
          prop="remark"
        />
        <el-table-column
          v-if="active == 2"
          label="海关编码提醒"
          align="center"
          prop=""
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:matching:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:matching:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div class="textcenter mt10">
        <el-button v-hasPermi="['source:detailData:query']" @click="goback"
          >上一步</el-button
        >
        <el-button
          type="primary"
          @click="downlMatchResults(2)"
          v-if="active == 1"
          >下载匹配结果</el-button
        >
        <el-upload
          class="upload-demo inline-block mx-10"
          ref="upload2"
          :limit="1"
          accept=".xlsx, .xls, .csv"
          :headers="upload.headers"
          :action="upload.url + '?type=' + upload.type"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress2"
          :on-success="handleFileSuccess2"
          :show-file-list="false"
          v-if="active == 1"
        >
          <el-button type="primary">重新上传文件</el-button>
        </el-upload>

        <!-- <el-button type="primary" @click="submitMatch"
          >在线编辑后重新提交匹配</el-button
        > -->
        <el-button type="primary" @click="nextStep" v-if="active == 1"
          >下一步</el-button
        >
        <el-button
          type="primary"
          @click="downlMatchResults(3)"
          v-if="active == 2"
          >下载匹配结果</el-button
        >
      </div>
    </div>

    <!-- 添加或修改数据匹配对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="EORI" prop="eori">
          <el-input v-model="form.eori" placeholder="请输入EORI" />
        </el-form-item>
        <el-form-item label="CLIENTS DESCRIPTION" prop="clientsDescription">
          <el-input
            v-model="form.clientsDescription"
            placeholder="请输入CLIENTS DESCRIPTION"
          />
        </el-form-item>
        <el-form-item
          label="CLIENTS DESCRIPTION IN CHINESE"
          prop="clientsDescriptionInChinese"
        >
          <el-input
            v-model="form.clientsDescriptionInChinese"
            placeholder="请输入CLIENTS DESCRIPTION IN CHINESE"
          />
        </el-form-item>
        <el-form-item label="MATERIAL" prop="material">
          <el-input v-model="form.material" placeholder="请输入MATERIAL" />
        </el-form-item>
        <el-form-item label="CLIENTS HS CODE" prop="clientsHsCode">
          <el-input
            v-model="form.clientsHsCode"
            placeholder="请输入CLIENTS HS CODE"
          />
        </el-form-item>
        <el-form-item label="ASIN" prop="asin">
          <el-input v-model="form.asin" placeholder="请输入ASIN" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="openJG" width="500px" append-to-body>
      <div>
        <i class="el-icon-circle-check fon green" />
        <div class="downlmplate download-template">
          成功导出匹配结果
          <div class="mt10 sky">{{ fileName }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveLocal">保存到本地</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="正在提交"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="askd">
        <el-progress :percentage="percentage"></el-progress>
        <div class="mt10">正在匹配数据</div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取消提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMatching,
  getMatching,
  delMatching,
  addMatching,
  quitUpload,
  updateDataMatchingLs,
  noticePy,
  deleteData,
  dataPro,
  delMatchingLs,
} from "@/api/system/matching";
import { getToken } from "@/utils/auth";
import { montage } from "@/utils/index";
export default {
  name: "Matching",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据匹配表格数据
      matchingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eori: null,
        clientsDescription: null,
        clientsDescriptionInChinese: null,
        material: null,
        clientsHsCode: null,
        asin: null,
        commodity: null,
        hsCode: null,
        thirdCountryDuty: null,
        matchingDegree: null,
        matchPattern: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      active: 0,
      openJG: false,
      fileList: [],
      fileName: "xznvczx.xlx",
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        type: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/matching/upload",
        uploadRequest: null, // 存储当前的上传请求对象
      },
      percentage: 0,
      dialogVisible: false,
    };
  },

  created() {
    this.active = JSON.parse(localStorage.getItem("active")) || 0;
    this.getList();
  },
  methods: {
    handleFileChange(file) {
      console.log(file);
      this.percentage = 0;
      if (file.status === "ready") {
        this.startUpload(file);
      }
    },
    handleFileError(error, file, fileList) {
      this.upload.isUploading = false;
      this.$modal.msgError("上传失败");
    },
    startUpload(file) {
      console.log(file);
      let size = file.size / 1024;
      let time = 100;
      console.log(Math.ceil(size));

      if (size < 400) {
        time = Math.ceil(size);
      } else {
        time = Math.ceil(size) + Math.ceil(size / 5);
      }
      if (!this.upload.isUploading) {
        this.dialogVisible = true;
        setInterval(() => {
          if (this.percentage < 98) {
            this.percentage += 1;
          } else {
            clearInterval();
          }
        }, time);
        this.$refs.upload.submit();
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response);
      this.upload.isUploading = false;
      if (this.dialogVisible) {
        if (response.code == 200) {
          this.dialogVisible = false;
          this.$modal.msgSuccess("上传成功");
          this.upload.open = false;
          this.$refs.upload.clearFiles();
          const loading = this.$loading({
            lock: true,
            text: "数据匹配中，请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          dataPro().then((res) => {
            loading.close();
            if (res.code == 200) {
              this.getList();
              this.percentage == 100;
              this.active++;
              localStorage.setItem("active", this.active);
            }
          });
        }
      }
    },
    // 文件上传中处理
    handleFileUploadProgress2(event, file, fileList) {
      this.upload.isUploading = true;
      this.loading = true;
    },
    // 文件上传成功处理
    handleFileSuccess2(response, file, fileList) {
      console.log(response);
      this.$refs.upload2.clearFiles();
      this.upload.isUploading = false;
      if (response.code == 200) {
        this.$modal.msgSuccess("上传成功");
        this.upload.open = false;
        this.upload.isUploading = false;
        this.loading = false;
        this.$refs.upload2.clearFiles();
        this.getList();
      }
    },
    // 取消上传
    cancelUpload() {
      this.dialogVisible = false;
      this.$refs.upload.clearFiles();
      quitUpload();
    },
    // 下一步导入
    handleConfirm() {
      this.getList();
      setTimeout(() => {
        if (
          this.matchingList &&
          this.matchingList.length > 0 &&
          this.total !== 0
        ) {
          this.active++;
          localStorage.setItem("active", this.active);
        }
      }, 1000);
    },
    // 下载模板
    downloadExcel() {
      this.download(
        "/system/matching/downloadFileLs",
        {},
        `文件模板_${new Date().getTime()}.xlsx`
      );
    },
    // 保存到本地
    saveLocal() {
      this.download(
        "system/matching/exportLs",
        {
          type: 3,
        },
        `匹配结果_${montage()}.xlsx`
      );
      setTimeout(() => {
        this.active = 0;
        localStorage.setItem("active", this.active);
        this.openJG = false;
        deleteData();
      }, 300);
    },
    nextStep() {
      noticePy();
      this.active++;
      localStorage.setItem("active", this.active);
      this.getList();
      this.queryParams.pageNum = 1;
    },
    goback() {
      this.active--;
      localStorage.setItem("active", this.active);
      this.queryParams.pageNum = 1;
      if (this.active == 0) {
        deleteData();
        this.matchingList = null;
      }
    },
    // 下载匹配结果
    downlMatchResults(c) {
      if (c == 2) {
        this.download(
          "system/matching/exportLs",
          {
            type: c,
          },
          `匹配结果_${montage()}.xlsx`
        );
      } else {
        this.openJG = true;
        this.fileName = `匹配结果_${montage()}.xlsx`;
      }
    },
    /** 查询数据匹配列表 */
    getList() {
      this.loading = true;
      setTimeout(() => {
        listMatching(this.queryParams).then((response) => {
          this.matchingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }, 1000);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        eori: null,
        clientsDescription: null,
        clientsDescriptionInChinese: null,
        material: null,
        clientsHsCode: null,
        asin: null,
        commodity: null,
        hsCode: null,
        thirdCountryDuty: null,
        matchingDegree: null,
        matchPattern: null,
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = JSON.parse(JSON.stringify(row));
      this.open = true;
      this.title = "修改数据匹配";
    },
    /** 提交按钮 */
    submitForm() {
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      updateDataMatchingLs(this.form).then((response) => {
        this.$modal.msgSuccess("提交成功");
        loading.close();
        this.getList();
        this.open = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除数据匹配编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMatchingLs(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.askd {
  padding: 40px 30px;
}
.mx-10 {
  margin: 0 10px;
}
.inline-block {
  display: inline-block;
}
.mt10 {
  margin-top: 10px;
}
.download-template {
  margin-left: 120px;
  margin-top: -10px;
  margin-bottom: 20px;
}
.fon {
  font-size: 40px;
  margin-left: 20px;
}
.downlmplate {
  margin-top: -30px;
}
.block {
  display: block;
}
.textcenter {
  text-align: center;
}
.mt30 {
  margin-top: 30px;
}
.mt60 {
  margin-top: 60px;
}
.absolute {
  position: absolute;
  left: 50%;
  top: 20%;
  translate: -50% 0;
}
.botlef {
  position: absolute;
  left: 50%;
  bottom: -20%;
}
.sky {
  color: #46a6ff;
}
.green {
  color: #13ce66;
}
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 60%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}
</style>
